// pages/chat/chat.js
const app = getApp();

Page({
  data: {
    inputText: "",
    messages: [],
    isLoading: false // 添加加载状态标志
  },
  
  onLoad() {
    this.loadHistory();
    this.setupWorkerListeners(); // 只在页面加载时设置一次监听器
  },
  
  // 初始化worker监听器
  setupWorkerListeners() {
    const worker = app.globalData.worker;
    
    worker.onMessage((res) => {
      const response = res.data;
      if (response.type === 'success') {
        this.appendMessage({ text: response.content, type: "customer" });
      } else if (response.type === 'error') {
        this.appendMessage({ 
          text: "抱歉，发生了错误：" + response.content, 
          type: "customer" 
        });
      }
      this.setData({ isLoading: false });
    });

    worker.onError((e) => {
      console.error('Worker error:', e);
      this.appendMessage({ 
        text: "抱歉，系统出现错误，请稍后再试", 
        type: "customer" 
      });
      this.setData({ isLoading: false });
    });
  },
  
  onInput(e) {
    this.setData({
      inputText: e.detail.value
    });
  },
  
  onSend() {
    const { inputText, isLoading } = this.data;
    if (!inputText.trim() || isLoading) return;

    // 设置加载状态，防止重复发送
    this.setData({ 
      inputText: "",
      isLoading: true 
    });
    
    // 添加用户消息
    this.appendMessage({ text: inputText, type: "user" });
    
    // 构建消息上下文
    const context = this.buildMessageContext();
    
    // 发送到worker
    const worker = app.globalData.worker;
    worker.postMessage(context);
  },
  
  // 构建带有上下文的消息
  buildMessageContext() {
    // 获取最近的5条消息作为上下文
    return this.data.messages.slice(-10).map(msg => ({
      role: msg.type === "user" ? "user" : "assistant",
      content: msg.text
    }));
  },
  
  appendMessage(message) {
    this.setData({
      messages: [...this.data.messages, message]
    });
    wx.setStorageSync('chat_history', this.data.messages);  // 保存历史记录
  },
  
  onNavigateToHistory() {
    wx.navigateTo({
      url: '/pages/history/history'
    });
  },
  
  loadHistory() {
    const history = wx.getStorageSync('chat_history') || [];
    this.setData({
      messages: history
    });
  }
});